#include "decorate.h"


void outputHelpInfomation()
{
    std::cout<<"Usage: embed option"<<std::endl
            <<"       embed source-file"<<std::endl
           <<"       embed source-file target-file"<<std::endl<<std::endl
          <<"Options: -h Show this message."<<std::endl
         <<"         -g The GUI version."<<std::endl<<std::endl
            <<"embed - A simple utility for transforming a script"<<std::endl
           <<"        into a C/C++ source file usable."<<std::endl<<std::endl;
    return;
}
int decorate(int argc,char *argv[])
{
    QFile sourceFile,targetFile;
    if(argc == 1)
    {
        outputHelpInfomation();
        return EXIT_FAILURE;
    }else if(argc == 2)
    {
        sourceFile.setFileName(argv[1]);
        targetFile.setFileName(QString(argv[1])+QString(".embed"));
    }else if(argc == 3)
    {
        sourceFile.setFileName(argv[1]);
        targetFile.setFileName(argv[2]);
    }else{
        outputHelpInfomation();
        return EXIT_FAILURE;
    }

    if(!sourceFile.open(QFile::ReadOnly | QFile::Text))
    {
        std::cerr<<"Error occured when opening source file "
                <<sourceFile.fileName().toStdString()<<":"<<std::endl
                   <<sourceFile.errorString().toStdString()<<std::endl;
        return EXIT_FAILURE;
    }
    if(!targetFile.open(QFile::WriteOnly | QFile::Text))
    {
        std::cerr<<"Error occured when opening target file "
                <<targetFile.fileName().toStdString()<<":"<<std::endl
                   <<targetFile.errorString().toStdString()<<std::endl;
        return EXIT_FAILURE;
    }

    std::cout<<"Converting..."<<std::endl;

    while(!sourceFile.atEnd())
    {
        QByteArray line;
        line = sourceFile.readLine();

        line.chop(1);
        for(int i=0;i<line.length();++i)
        {
            if((line.at(i)=='\\')||(line.at(i)=='\'')||(line.at(i)=='\"')||(line.at(i)=='\?'))
            {
                line.insert(i,'\\');
                ++i;
            }
        }

        if(!QString(line).isEmpty())
        {
            targetFile.write("\""+line+"\\n\"\n");
        }
    }
    std::cout<<"Done."<<std::endl;

    return EXIT_SUCCESS;
}
